package com.mano233.server.controller;

import com.mano233.server.po.ResponseMessage;
import com.mano233.server.po.ResponseStatus;
import com.mano233.server.service.serviceImpl.FastDfsServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author mano233
 */
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
public class UploadController {
    private static Logger logger = LoggerFactory.getLogger(UploadController.class);
    private FastDfsServiceImpl fastDfsServiceImpl;

    @Autowired
    public UploadController(FastDfsServiceImpl fastDfsServiceImpl) {
        this.fastDfsServiceImpl = fastDfsServiceImpl;
    }

    @PostMapping("/uploadFile")
    public ResponseMessage singleFileUpload(@RequestParam("upload") MultipartFile file) {
        String url = "";
        if (file.isEmpty()) {
            return new ResponseMessage(ResponseStatus.ERROR, "上传文件不能为空");
        }
        try {
            url = fastDfsServiceImpl.saveFile(file);
        } catch (Exception e) {
            logger.error("upload file failed", e);
        }
        ResponseMessage returnMessage = new ResponseMessage(ResponseStatus.SUCCESS);
        returnMessage.setFileName(file.getOriginalFilename());
        returnMessage.setUploaded(true);
        returnMessage.setUrl(url);
        return returnMessage;
    }
}